<?php
/**
 * WxTempMsg.class.php
 * 微信模板消息类
 *
 * @author  王中艺
 * @date    2016-11-24
 */

namespace Wechat\Util;
use Common\Model\UserModel;

class WxTempMsg {
    private static $self;

    public $wechat, $errMsg, $errCode, $redis, $queueKey;

    function __construct(){
        $this->wechat   = \Wechat\Util\WechatExt::getInstance();
        $this->redis    = \Common\Util\Redis::getInstance();
        $this->queueKey = 'xinletu_wechat_message_queue';
    }

    static function getInstance(){
        if(!self::$self){
            self::$self     = new self();
        }

        return self::$self;
    }

    /**
     * 积分变动模板消息
     * @param   $userInfo
     * @param   $score      积分变动值
     * @param   $type       积分变动类型
     * @param   $pre 是否加入队列准备，否：立即推送
     * @return  boolean
     */
    function sendScoreTempMsg($userInfo, $score, $type, $pre = true){
        if($pre === true){
            //将消息信息加入redis队列
            $info   = array(
                'user_info'     => $userInfo,
                'score' => $score,
                'type'  => $type,
                'msg_cate'  => 1
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }
        $remark     = '积分详情请查看相关记录!';
        switch($type){
            case 1: 
                $typeName   = '消费返利';   
                $action     = 1;
                $first     = sprintf(
                    "恭喜你，在正心源消费成功，获得了%d幸福豆，快去幸福商城看看吧！",
                    $score
                );
            break;
            case 2:
                $typeName   = '发展下线';
                $action     = 1;
                $first  = sprintf(
                    "恭喜你成功拉拢了一名家长入伙，获得了%d幸福豆，快去幸福商城看看吧！",
                    $scope
                );
            case 3: 
                $typeName   = '分享我们';   
                $action     = 1;
                $first     = sprintf(
                    "恭喜你，成功分享正心源课程，获得了%d幸福豆，快去幸福商城看看吧！",
                    $score
                );
            break;
            case 4: 
                $typeName   = '观看课程';   
                $action     = 1;
                $first     = sprintf(
                    "恭喜你，顺利观看完课程，获得了%d幸福豆，快去幸福商城看看吧！",
                    $score
                );
                $remark     = '赶快去领取毕业证吧!';
            break;
            case 5: 
                $typeName   = '课程兑换';   
                $action     = 2;
                $first     = sprintf(
                    "恭喜你成功兑换正心源课程，消耗%d幸福豆!", $score
                );
            break;
            case 6: 
                $typeName   = '完善信息';   
                $action     = 1;
                $first     = sprintf(
                    "恭喜你顺利完善了个人信息，获得了%d幸福豆！", $score
                );
            break;
            case 7: 
                $typeName   = '问题反馈';   
                $action     = 1;
                $first     = sprintf(
                    "恭喜你，你在%s提交的反馈意见被老师采纳，获得了%d幸福豆！快去幸福商城看看吧！",
                    date('m月d日'), $score
                );
            break;
            case 8:
                $typeName   = '下线购买';
                $action     = 1;
                $first  = sprintf(
                    "恭喜你分享的用户在%s成功购买了正心源课程，你获得了%d幸福豆！快去幸福商城看看吧！",
                    date('m月d日'), $score
                );
            break;
            default: return false; break;
        }

        $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/score');
        $tempId     = 'J0oQfp3N7L3nijEzzKC3JPCGgr4TtNCGxpAjAid1d9s';    //正式模板ID
        $tempInfo   = [
            'touser'    => $userInfo['open_id'],
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => [
                'first' => ['value' => $first],
                'keyword1'  => ['value' => date('Y-m-d H:i:s')],
                'keyword2'  => ['value' => $typeName],
                'keyword3'  => ['value' => $action ? '增加' : '支出'],
                'keyword4'  => ['value' => $action ? $score : 0],
                'keyword5'  => ['value' => $action ? 0 : $score],
                'remark'    => ['value' => $remark]
            ]
        ];

        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
        } 
    }

    /**
     * 角色更改消息推送
     * @param   $id     目标角色的用户ID或open_id
     * @param   $userInfo   用户信息
     * @param   $pre 是否加入队列准备，否：立即推送
     * @param   $oldRole 用户之前的角色ID
     * @return  $boolean [<description>]
     */
    function changeRole($id, $userInfo, $oldRole, $pre = true){
        if($pre === true){
            $info   = array(
                'id'    => $id,
                'user_info' => $userInfo,
                'old_role'  => $oldRole,
                'msg_cate'  => 2
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }
        //是否为角色转换判定
        if($oldRole <= 100 || $userInfo['role_id'] == $oldRole)
            return false;

        //目标用户openid获取
        if(is_numeric($id)){
            $openId     = M('t_user', null)
                ->where('id = %d', $id)
                ->cache(true)
                ->getField('open_id');
        }else{
            $openId     = $id;
        }

        if($openId == $userInfo['open_id']){
            //向本人发送消息
            $first     = sprintf(
                "恭喜您于%s成功从%s角色转换为%s角色",
                date('Y-m-d H:i:s'), 
                $this->_getRoleName($oldRole),
                $this->_getRoleName($userInfo['role_id'])
            );
            $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/info');
        }else{
            //向上级发送消息
            $first     = sprintf(
                "恭喜您，组织里面的%s于%s成功从%s角色转为%s角色",
                $userInfo['nickname'],
                date('Y-m-d H:i:s'),
                $this->_getRoleName($oldRole),
                $this->_getRoleName($userInfo['role_id'])
            );
            $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/Sole/statis');
        }
        $tempId     = '09F2y84ziPFC_-beC7cAsVkCdPRdQk9Oy-icAFUeFJI';    //正式模板ID
        $tempInfo   = array(
            'touser'    => $openId,
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => array(
                'first'     => array('value' => $first),
                'keyword1'  => array('value' => $this->_getRoleName($oldRole)),
                'keyword2'  => array('value' => $this->_getRoleName($userInfo['role_id'])),
                'keyword3'  => array('value' => '永久'),
                'remark'    => array('value' => '详情信息请点击查看!')
            )
        );
        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
        }
    }

    /**
     * 提现结果消息推送
     * @param   $userInfo 用户信息必须[open_id]
     * @param   $wdInfo 提现信息
     * @param   $pre 是否加入队列准备，否：立即推送
     * @param   $succes 是否成功
     */
    function withdraw($userInfo, $wdInfo, $success, $pre = true){
        if($pre === true){
            $info   = array(
                'user_info' => $userInfo, 
                'wd_info'   => $wdInfo,
                'success'   => $success,
                'msg_cate'  => 3
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }
        if($success){
            $first     = sprintf(
                "恭喜，您于%s申请的提现已经通过审核，提现总金额%.2f元，缴纳税率%.2f%%，".
                "剩余%.2f已成功打入您的微信钱包，请查收",
                date('Y-m-d'), 
                round($wdInfo['amount'],2), 
                round($wdInfo['tax_rate']*100 ,2), 
                round($wdInfo['amount']*(1-$wdInfo['tax_rate']), 2)
            );
        }else{
            $first     = sprintf(
                "您于%s提交的提现申请未通过审核，请联系管理员!",
                date('Y-m-d'), $wdInfo['amount']
            );
        }

        $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/Sole/withdraw_log');
        $tempId     = '5AW3ssyvQzOAqcLJU84YMoFNfTF4k-8ot34lSnGDjKw';    //正式模板ID
        $tempInfo   = array(
            'touser'    => $userInfo['open_id'],
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => array(
                'first'    => array('value' => $first),
                'keyword1'  => array('value' => date('Y-m-d H:i:s', $wdInfo['create_time'])),
                'keyword2'  => array('value' => $wdInfo['amount']),
                'keyword3'  => array(
                    'value' => $success ? '审核成功' : '审核失败', 
                    'color' => $success ? '#4EC653' : '#FE8566'
                ),
                'remark'    => array('value' => '详情信息请联系管理员')
            )
        );

        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
        }
    }

    /**
     * 购买课程模板消息
     * @param  string $userInfo     用户信息
     * @param  array  $courseInfo   课程信息
     * @param  array  $payInfo  支付信息
     * @param   $pre 是否加入队列准备，否：立即推送
     * @return boolean             [description]
     */
    function buyCourse($userInfo, $courseInfo, $payInfo, $pre = true){
        if($pre === true){
            $info   = array(
                'user_info' => $userInfo,
                'course_info'   => $courseInfo,
                'pay_info'  => $payInfo,
                'msg_cate'  => 4
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }
        $first     = sprintf(
            "恭喜，您于%s成功购买《%s》，感谢您的支持!",
            date('Y-m-d H:i:s'),
            $courseInfo['name']
        );

        $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/course');
        $tempId     = '_af-ZDQXWQuerbzY9VyrMXAWmyJaafONEUCyw3ntot8c';    //正式模板ID
        $tempInfo   = array(
            'touser'    => $userInfo['open_id'],
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => array(
                'name'  => ['value' => $courseInfo['name']],
                'remark'    => ['value' => $first]
            )
        );

        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
        }
    }

    /**
     * 上级用户变更通知
     * @param   $userInfo 用户信息
     * @param   $fatherInfo 上级信息
     * @param   $pre 是否加入队列
     * @return  boolean [<description>]
     */
    function changeFather($userInfo, $fatherInfo, $pre = true){
        //幸福家长角色不发送
        if($userInfo['role_id'] == 106)
            return true;

        //加入队列
        if($pre === true){
            $info   = array(
                'user_info' => $userInfo,
                'fater_info'   => $fatherInfo,
                'msg_cate'  => 5
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }

        $first  = sprintf(
            '您的上级已被管理员指定为%s，若有疑问请联系管理员！', 
            $faterInfo['nickname']
        );

        $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/index');
        $tempId     = '';    //正式模板ID
        $tempId     = 'UGBCFi-ikvkuDDiN9labt77II-bqAaOfowkwsvM4290';    //测试模板ID
        $tempInfo   = array(
            'touser'    => $userInfo['open_id'],
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => array(
                'first'    => array('value' => $first),
                'keyword1'  => array('value' => $userInfo['nickname']),
                'keyword2'  => array('value' => $fatherInfo['nickname']),
                'keyword3'  => array('value' => '010-82826598'),
                'keyword4'  => array('value' => date('Y-m-d H:i:s')),
                'remark'    => array('value' => '详情信息请联系管理员!')
            )
        );

        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
            return false;
        }
        return true;
    }

    /**
     * 下级用户添加通知
     * @param   $userInfo 用户信息
     * @param   $childInfo 自用户信息
     * @param   $pre 是否加入队列
     * @return  boolean
     */
    function addChild($userInfo, $childInfo, $pre = true){
        if($pre === ture){
            $info   = array(
                'user_info' => $userInfo,
                'child_info'   => $childInfo,
                'msg_type'  => 6
            );
            $this->redis->rpush($this->queueKey, json_encode($info));
            return true;
        }

        $first  = sprintf(
            '恭喜您，有一名新成员(%s)加入您的组织,角色为%s!', 
            $childInfo['nickname'],
            $this->_getRoleName($childInfo['role_id'])
        );

        $url    = $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/index');
        $tempId     = 'JR4W3bU9sjET42Dp8kvDJtYPNN7bUrZqdfyUnJUvPbU';    //正式模板ID
        $tempInfo   = array(
            'touser'    => $userInfo['open_id'],
            'template_id'   => $tempId,
            'url'   => $url,
            'topcolor'  => '#FF0000',
            'data'  => array(
                'first'    => array('value' => $first),
                'keyword1'  => array('value' => $this->_getRoleName($childInfo['role_id'])),
                'keyword2'  => array('value' => date('Y-m-d H:i:s')),
                'keyword3'  => array('value' => $childInfo['nickname']),
                'remark'    => array('value' => '详情信息请联系管理员!')
            )
        );

        $result     = $this->wechat->sendTemplateMessage($tempInfo);
        if($result === false){
            $this->errCode  = $this->wechat->errCode;
            $this->errMsg   = $this->wechat->errMsg;
            return false;
        }
        return true;
    }

    /**
     * 获取用户角色名称
     * @param   $roleId
     * @return  $roleName
     */
    private function _getRoleName($roleId){
        $roleInfo   = UserModel::ROLE_MAP;
        if(isset($roleInfo[$roleId]))
            return  $roleInfo[$roleId];

        return '幸福家长';
    }
}
